import { Component } from 'react'
import { render as render_ReactDom, unmountComponentAtNode } from 'react-dom';

/**
 * 功能组件
 */
export default class GmTeleport extends Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      popup: null
    }
  }
  private _renderTeleport() {
    if (!this.state.popup) return;
    // @ts-ignore
    render_ReactDom(this.props.children, this.state.popup);
  }
  componentDidMount() {
    //新建一个div标签并塞进body
    const oPopup = document.createElement("div");
    oPopup.className = "teleport"
    this.setState({ popup: oPopup }, () => {
      document.body.appendChild(this.state.popup);
      this._renderTeleport();
    })
  }
  componentDidUpdate() {
    this._renderTeleport();
  }
  componentWillUnmount() {
    if (!this.state.popup) return;
    //在组件卸载的时候，保证弹层也被卸载掉
    unmountComponentAtNode(this.state.popup);
    document.body.removeChild(this.state.popup);
  }
  render() {
    return null;
  }
}
